#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        stack<pair<TreeNode*, int>> s;
        s.push(make_pair(root, 0));
        while (s.size())
        {
            auto tmp = s.top();
            s.pop();
            if (tmp.first != nullptr)
            {
                if (tmp.second == 0)
                {
                    s.push(make_pair(tmp.first, 1));
                    s.push(make_pair(tmp.first->left, 0));
                }
                else if (tmp.second == 1)
                {
                    s.push(make_pair(tmp.first, 2));
                    s.push(make_pair(tmp.first->right, 0));
                }
                else
                {
                    ret.push_back(tmp.first->val);
                }
            }
        }
        return ret;
    }
};